<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="主键ID" prop="id">
        <el-input
          v-model="queryParams.id"
          placeholder="请输入主键ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择状态"
          clearable
        >
          <el-option
            v-for="dict in status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="推广状态" prop="isAd">
        <el-select
          v-model="queryParams.isAd"
          placeholder="请选择推广状态"
          clearable
        >
          <el-option
            v-for="dict in is_ad"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['productManage:product:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['productManage:product:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['productManage:product:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['productManage:product:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="productList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键ID" align="center" prop="id" />
      <el-table-column label="名称" align="center" prop="name" />
      <el-table-column label="类目" align="center" prop="categoryName" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="图片" align="center" prop="image" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.image" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="销售价格" align="center" prop="salePrice" />
      <el-table-column label="进货价格" align="center" prop="costPrice" />
      <el-table-column label="库存量" align="center" prop="stock" />
      <el-table-column label="销量" align="center" prop="sold" />
      <el-table-column label="推广状态" align="center" prop="isAd">
        <template #default="scope">
          <dict-tag :options="is_ad" :value="scope.row.isAd" />
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="180"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['productManage:product:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['productManage:product:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="productRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <!-- 商品管理下拉树 -->
        <el-form-item label="类目" prop="parentId">
          <el-tree-select
            v-model="form.categoryId"
            :data="categoryOptions"
            :props="{
              value: 'id',
              label: 'categoryName',
              children: 'children',
            }"
            value-key="id"
            placeholder="请选择类目"
            check-strictly
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in status"
              :key="dict.value"
              :label="parseInt(dict.value)"
              >{{ dict.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="图片" prop="image">
          <image-upload v-model="form.image" />
        </el-form-item>
        <el-form-item label="排序" prop="productSort">
          <el-input v-model="form.productSort" placeholder="请输入排序" />
        </el-form-item>
        <el-form-item label="销售价格" prop="salePrice">
          <el-input v-model="form.salePrice" placeholder="请输入销售价格" />
        </el-form-item>
        <el-form-item label="进货价格" prop="costPrice">
          <el-input v-model="form.costPrice" placeholder="请输入进货价格" />
        </el-form-item>
        <el-form-item label="介绍" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
        <el-form-item label="库存量" prop="stock">
          <el-input v-model="form.stock" placeholder="请输入库存量" />
        </el-form-item>
        <el-form-item label="销量" prop="sold">
          <el-input v-model="form.sold" placeholder="请输入销量" />
        </el-form-item>
        <el-form-item label="推广状态" prop="isAd">
          <el-select v-model="form.isAd" placeholder="请选择推广状态">
            <el-option
              v-for="dict in is_ad"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Product">
import {
  listProduct,
  getProduct,
  delProduct,
  addProduct,
  updateProduct,
} from "@/api/productManage/product";
import { getCategory, listCategory } from "@/api/categoryManage/category";
const { proxy } = getCurrentInstance();
const { status, is_ad } = proxy.useDict("status", "is_ad");

const productList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    id: null,
    name: null,
    status: null,
    isAd: null,
  },
  rules: {
    name: [{ required: true, message: "名称不能为空", trigger: "blur" }],
    categoryId: [{ required: true, message: "类目不能为空", trigger: "blur" }],
    salePrice: [
      { required: true, message: "销售价格不能为空", trigger: "blur" },
    ],
    costPrice: [
      { required: true, message: "进货价格不能为空", trigger: "blur" },
    ],
    stock: [{ required: true, message: "库存量不能为空", trigger: "blur" }],
  },
});
//类别下拉树
const categoryOptions = ref([]);

const { queryParams, form, rules } = toRefs(data);

/** 查询商品管理列表 */
function getList() {
  loading.value = true;
  listProduct(queryParams.value).then((response) => {
    productList.value = response.rows;
    total.value = response.total;
    // 遍历商品列表，获取每个商品的类别名称
    const promises = productList.value.map((product) => {
      product.salePrice = product.salePrice / 100;
      product.costPrice = product.costPrice / 100;
      return getCategory(product.categoryId).then((categoryResponse) => {
        // 将类别名称添加到商品对象中
        product.categoryName = categoryResponse.data.categoryName || "未知类别";
        return product;
      });
    });
    // 等待所有请求完成
    Promise.all(promises).then(() => {
      loading.value = false;
      // console.log(productList.value);
    });
  });
}

/** 查询商品类目管理下拉树结构 */
function getTreeselect() {
  listCategory().then((response) => {
    categoryOptions.value = [];
    const data = { id: 0, categoryName: "顶级节点", children: [] };
    data.children = proxy.handleTree(response.data, "id", "parentId");
    categoryOptions.value.push(data);
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    categoryId: null,
    status: null,
    image: null,
    productSort: null,
    salePrice: null,
    costPrice: null,
    description: null,
    stock: null,
    sold: null,
    isAd: null,
    createTime: null,
    createBy: null,
    updateTime: null,
    updateBy: null,
    remark: null,
  };
  proxy.resetForm("productRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  getTreeselect();
  open.value = true;
  title.value = "添加商品管理";
}

/** 修改按钮操作 */
async function handleUpdate(row) {
  reset();
  await getTreeselect();
  const _id = row.id || ids.value;
  getProduct(_id).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改商品管理";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["productRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != null) {
        updateProduct(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addProduct(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除商品管理编号为"' + _ids + '"的数据项？')
    .then(function () {
      return delProduct(_ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "productManage/product/export",
    {
      ...queryParams.value,
    },
    `product_${new Date().getTime()}.xlsx`
  );
}

getList();
</script>
